// [1493]删掉一个元素以后全为 1 的最长子数组
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
use std::cmp::max;
impl Solution {

    /*
    思路分析：
    想通过滑动窗口的方式计算
    问题：
    1. 左指针什么时候移动
    2. 右指针什么时候移动
    3. 答案什么时候更新
    反思：
    1. 边界问题
    2. 索引相同情况
    3. 多写测试用例，不要局限于官方给的例子
     */
    pub fn longest_subarray2(nums: Vec<i32>) -> i32 {
        let mut last_cache = 0i32;
        let mut ans = 0i32;
        let mut left = 0i32;
        for (i, &num) in nums.iter().enumerate() {
            if num == 0 {
                let dec = if nums[left as usize] == 1 {0} else {1};
                let cur = max(i as i32 - left - dec, 0);
                ans = ans.max(last_cache + cur);
                last_cache = cur;
                left = i as i32;
            }
        }
        let cur = max(nums.len() as i32 - left - 1, 0);
        ans = ans.max(last_cache + cur);
        ans
    }

    pub fn longest_subarray(nums: Vec<i32>) -> i32 {
        // 动态滑动窗口
        // 定义状态：窗口内0的个数大于1
        let mut cnt = 0; // 统计0的个数
        let mut ans = 0;
        let mut left = 0;
        for (right, &num) in nums.iter().enumerate() {
            // right加入窗口
            cnt += 1 - num;
            // 满足条件
            while cnt > 1 {
                // left移出窗口，根据情况更新答案
                cnt -= 1 - nums[left];
                left += 1;
            }
            // 不满足条件，根据情况更新答案
            ans = ans.max(right - left)
        }
        ans as _
    }
}
//leetcode submit region end(Prohibit modification and deletion)


#[test]
fn main() {
    let nums = vec![1,1,0,1];
    assert_eq!(Solution::longest_subarray(nums), 3);
    let nums = vec![0,1,1,1,0,1,1,0,1];
    assert_eq!(Solution::longest_subarray(nums), 5);
    let nums = vec![1,1,1];
    assert_eq!(Solution::longest_subarray(nums), 2);
    let nums = vec![0,1,1,1];
    assert_eq!(Solution::longest_subarray(nums), 3);
    let nums = vec![1,1,1,0];
    assert_eq!(Solution::longest_subarray(nums), 3);
    let nums = vec![1,1,0,0,1,1,1,0,1];
    assert_eq!(Solution::longest_subarray(nums), 4);
}